<?php
/**
 * 商品管理
 *
 *
 *
 *
 * by www.besonit.com
 */
defined('BYshopJL') or exit('Access Invalid!');

class goods_share_viewModel extends Model
{
    public function __construct()
    {
        parent::__construct('bs_share_view');
    }

    /**
     * updateGoodsShareView
     * 更新分享浏览记录
     * @param $goods_id
     * @return bool
     */
    public function updateGoodsShareView($goods_id, $member_id, $url)
    {
        if (empty($goods_id) || empty($member_id) || empty($_GET['rec']) || empty($url)) return false;
        $rec = trim($_GET['rec']);
        $url_md5 = md5($url);
        $member_model = Model('member');
        $goods_model = Model('goods');

        //判断分享链接正确性
        $member_info = $member_model->infoMember(array('share_sign' => $rec));
        if ($member_info['member_id'] == $member_id) return false;
        $member_id = $member_info['member_id'];

        //判断商品正确性
        $count = $goods_model->getGoodsCount(array('goods_id' => $goods_id));
        if ($count == 0) return false;


        $year_month = mktime(0, 0, 0, date('m'), 1, date('Y'));
        $view_count = $this->query("SELECT COUNT('goods_id') FROM {$this->table_prefix}bs_share_view WHERE  `year_month`=$year_month AND `goods_id`=$goods_id AND `member_id`=$member_id AND `url_md5`='$url_md5'");
        if (intval($view_count[0]["COUNT('goods_id')"]) == 0) {
            $sql = "INSERT INTO {$this->table_prefix}bs_share_view  (`member_id`,`goods_id`,`year_month`,`url_md5`,`url`,`month_view`,`d" . date('d') . "`) VALUES($member_id,$goods_id,$year_month,'$url_md5','$url',1,1)";
        } else {
            $sql = "UPDATE {$this->table_prefix}bs_share_view SET `d" . date('d') . "`= `d" . date('d') . "`+1 ,`month_view` = `month_view`+1 WHERE `year_month`=$year_month AND `goods_id`=$goods_id AND `member_id`=$member_id";
        }
        $flag = $this->query($sql);
        return true;
    }

    /**
     * getShareList
     * 获取分享列表
     * @param $condition
     * @param int $page
     * @return array
     */
    public function getShareList($condition,$page=10)
    {
        $data_list = $this->table('bs_share_view,member')
            ->field('bs_share_view.member_id,bs_share_view.goods_id,bs_share_view.url,bs_share_view.month_view,bs_share_view.year_month,member.member_mobile')
            ->join('left')->on('bs_share_view.member_id = member.member_id')
            ->where($condition)->page($page)->select();
        if (empty($data_list)) return array();
        return $data_list;

    }
}
